package flate

import (
	"bytes"
	"compress/flate"
	"io"
	"os"
)

func Compress(readByte []byte) ([]byte, error) {
	buf := bytes.NewBuffer(nil)
	// 创建一个flate.Writer
	flateWrite, err := flate.NewWriter(buf, flate.BestCompression)
	if err != nil {
		return nil, err
	}
	defer flateWrite.Close()
	// 写入待压缩内容
	_, err = flateWrite.Write(readByte)
	if err != nil {
		return nil, err
	}
	err = flateWrite.Flush()
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

func UncompressedByFile(f *os.File) ([]byte, error) {
	buf := bytes.NewBuffer(nil)
	_, err := buf.ReadFrom(f)
	if err != nil {
		return nil, err
	}

	flateReader := flate.NewReader(buf)
	defer flateReader.Close()
	// 输出
	wt := bytes.NewBuffer(nil)
	_, _ = io.Copy(wt, flateReader)
	return wt.Bytes(), nil
}

func UncompressedByte(b []byte) ([]byte, error) {
	buf := bytes.NewBuffer(b)
	flateReader := flate.NewReader(buf)
	defer flateReader.Close()
	// 输出
	wt := bytes.NewBuffer(nil)
	_, _ = io.Copy(wt, flateReader)
	return wt.Bytes(), nil
}

